//
//  SMLoginInfo.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/16.
//

import SwiftUI
import Combine

let loginKey = "isUserLoggedIn"
let tokenKey = "userToken"

class SMLoginInfo: ObservableObject {
    static let shared = SMLoginInfo()
    
    @Published var shouldPresentLogInView: Bool = false
    private var cancellables = Set<AnyCancellable>()
    
    var isLogined: Bool {
        return SMUserDefaults.shared.retrieveBoolean(for: SMAccountIdentifier, default: false)
    }
    
    private init() {
        NotificationCenter.default.publisher(for: .logoutNotification, object: nil)
            .sink { [weak self] notification in
                guard let self = self else { return }
                self.logout()
            }
            .store(in: &cancellables)
        
        NotificationCenter.default.publisher(for: .loginInvalidNotification, object: nil)
            .sink { [weak self] notification in
                guard let self = self else { return }
                self.loginInvalid()
            }
            .store(in: &cancellables)
    }
    
    func logSuccess() {
        SMUserDefaults.shared.saveBoolean(true, for: SMAccountIdentifier)
    }

    func loginInvalid() {
        // 清除所有登录信息
        SMUserDefaults.shared.removeEntry(for: SMAccountIdentifier)
        shouldPresentLogInView = true
        print("登录失效")
    }
    
    func logout() {
        SMUserDefaults.shared.removeEntry(for: SMAccountIdentifier)
        SMAppState.shared.rootView = .login
        print("用户已退出登录")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
